﻿using System.Collections;
using UnityEngine;
using winS.Unity;
using Coroutine = winS.Unity.Coroutine;

public static class AnimatorExtension
{
    /// <summary>
    /// 等待直到当前状态播放结束.
    /// <para>仅在当前播放的状态没有任何过渡(将Animator当Animation使用)的情况下, 该方法才会生效</para>
    /// </summary>
    /// <param name="disableWhenFinished">如果为true,则在结束时禁用<paramref name="self"/></param>
    public static Coroutine WaitUntilFinished(this Animator self, bool disableWhenFinished = false)
    {
        return CoroutineStarter.Start(WaitUntilFinishedProcess(self, disableWhenFinished));
    }

    private static IEnumerator WaitUntilFinishedProcess(Animator animator, bool disableWhenFinished)
    {
        AnimatorStateInfo animatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
        yield return Coroutine.Wait(animatorStateInfo.length * (1 - (animatorStateInfo.normalizedTime - (int)animatorStateInfo.normalizedTime)));
        if (disableWhenFinished) animator.enabled = false;
    }
}
